// eslint-disable-next-line no-unused-vars
import nodeFetch, { Headers, RequestInit } from 'node-fetch';
import apiPathTranslator from './apiPathTranslator';
import { getDeviceToken } from './deviceToken';

type BodyInit = string;
type RequestRedirect = 'follow' | 'error' | 'manual';
type FetchResponseType =
  | 'basic'
  | 'cors'
  | 'default'
  | 'error'
  | 'opaque'
  | 'opaqueredirect';

export interface FetchOptions {
  method?: string;
  headers?: Headers;
  body?: BodyInit;
  redirect?: RequestRedirect;

  // node-fetch extensions
  timeout?: number;
  compress?: boolean;
  size?: number;
  follow?: number;
}

export interface FetchResponse {
  ok: boolean;
  status: number;
  statusText: string;
  url: string;
  type: FetchResponseType;
  size: number;
  headers: Headers;
  bodyUsed: boolean;

  json(): Promise<any>;

  text(): Promise<string>;

  buffer(): Promise<Buffer>;
}

// Usage:
//   fetch2使用时，可以在url中使用'<merlin>','<castle>'等前缀，表示从特定的服务中请求
//   指定的资源。
// Example:
//   define(
//     'GET /test',
//     { auth: true },
//     async (req, res) => {
//       const r = await fetch2('<merlin>/meeting', {
//         method: 'GET',
//         headers: {
//           cookie: req.headers.cookie,
//         }
//       });
//       res.json(await r.json());
//     }
//   );
async function fetch2(
  url: string,
  options: RequestInit,
): Promise<FetchResponse> {
  const token = getDeviceToken();
  if (token) {
    options.headers = {
      ...options.headers,
      device_token: token
    };
  }
  console.log(`fetch2(${url}) <actually url is ${apiPathTranslator(url)}>`);
  return nodeFetch(apiPathTranslator(url), options);
}

export default fetch2;
